package com.shop.service.impl;

import com.shop.constant.Constants;
import com.shop.dao.CommentDao;
import com.shop.entity.Comment;
import com.shop.entity.CommentDetailVO;
import com.shop.exception.AddCommentErrorException;
import com.shop.exception.DAOException;
import com.shop.exception.DeleteCommentErrorException;
import com.shop.exception.getCommentErrorException;
import com.shop.factory.ObjectFactory;
import com.shop.service.CommentService;
import com.shop.transaction.TransactionManager;

import java.util.List;

public class CommentServiceImpl implements CommentService {

    private static CommentDao dao = (CommentDao) ObjectFactory.getInstance(Constants.COMMENT_DAO_KEY);

    @Override
    public List<CommentDetailVO> getGDCommentsById(int gd_id,int pageNum,int pageSize) throws getCommentErrorException {
        return dao.queryAllCommentBy_GDID(gd_id,pageNum,pageSize);

    }

    @Override
    public int deleteCommentsById(int c_id) throws DeleteCommentErrorException {
        int result = 0;
        TransactionManager tm = new TransactionManager();
        try {
            tm.openTransaction();
            result = dao.deleteCommentById(c_id);
            if(result == -1){
                throw new DeleteCommentErrorException();
            }
            tm.commit();

        } catch (DAOException e) {
            e.printStackTrace();
            try {
                tm.rollback();
                throw new DAOException(e);
            } catch (DAOException daoException) {
                daoException.printStackTrace();
            }finally {
                TransactionManager.close();
            }
        }

        return result;
    }

    @Override
    public int addComments(Comment comment) throws AddCommentErrorException {
        int result = 0;
        TransactionManager tm = new TransactionManager();
        try {
            tm.openTransaction();
            result = dao.addComment(comment);
            if(result == -1){
                throw new AddCommentErrorException("评论添加失败！");
            }
            tm.commit();

        } catch (DAOException e) {
            e.printStackTrace();
            try {
                tm.rollback();
                throw new DAOException(e);
            } catch (DAOException daoException) {
                daoException.printStackTrace();
            }finally {
                TransactionManager.close();
            }
        }

        return result;
    }


//    public static void main(String[] args) throws AddCommentErrorException {
//        Comment comment = new Comment();
//        //1.��ȡ����
//
//        //2.�������
//        comment.setC_content("���۲���2");
//        comment.setGd_id(1);
//        comment.setU_id(1);
//
//        CommentServiceImpl service = new CommentServiceImpl();
//        System.out.println(service.addComments(comment));
//
//    }
}
